<template>
  <div @submit="handleSubmit">
    <a-form :form="form">
      <!--companyId-->
      <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="所属公司">
        <a-select
          @change="handleProvinceChange"
          v-decorator="[ 'companyId', {rules: [{ required: true, message: '请选择所属公司' }],initialValue:defaultCompany}]"
          placeholder="请选择所属公司">
          <a-select-option :value="company.id" v-for="company in companyList" :key="company.id">
            {{company.name}}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="适用商户">
        <a-tree-select
          style="width:300px"
          :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder='请选择商户'
          allowClear
          multiple
          treeDefaultExpandAll
          :treeData="treeData"
          v-decorator="['value',{rules: [{ required: true, message: '请选择商户' }]}]"
        >
          <span style="color:#08c" slot="title" slot-scope="{key}"
          >
            {{value}}
          </span>>
        </a-tree-select>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="批次号">
        <a-input placeholder="批次号"
                 v-decorator="[ 'couponStockId', {rules: [{ required: true, message: '请输入批次号' }]}]"
        ></a-input>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商户id">
        <a-input placeholder="微信子商户id"
                 v-decorator="[ 'paySubMchId',{rules: [{ required: true, message: '请输入微信子商户id' }]}]"
        ></a-input>
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="优惠券别名">
        <a-input placeholder="优惠券别名"
                 v-decorator="[ 'name', {rules: [{ required: true, message: '请输入优惠券别名' }]}]"
        ></a-input>
      </a-form-item>

      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="优惠券图"
      >
        <a-upload
          :action="this.$baseURL+'/common/upload/uploadImg'"
          listType="picture-card"
          :fileList="fileList"
          @preview="uploadPreview"
          @change="uploadChange"
        >
          <div v-if="fileList.length < 1">
            <a-icon type="plus"/>
            <div class="ant-upload-text">上传优惠券图</div>
          </div>
        </a-upload>
        <a-modal :visible="previewVisible" :footer="null" @cancel="uploadCancel">
          <img alt="example" style="width: 100%" :src="previewImage"/>
        </a-modal>
      </a-form-item>

      <!--note 简介描述 -->
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="简介描述">
        <!--v-model="content"-->
        <quill-editor
          v-model="content "
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
          @change="onEditorChange($event)">
        </quill-editor>
      </a-form-item>

      <a-form-item
        v-bind="buttonCol"
      >
        <a-row>
          <a-col span="6">
            <a-button type="primary" html-type="submit">提交</a-button>
          </a-col>
          <a-col span="10">
            <a-button @click="handleGoBack">返回</a-button>
          </a-col>
          <a-col span="8"></a-col>
        </a-row>
      </a-form-item>

    </a-form>
  </div>
</template>

<script>


  import pick from 'lodash.pick'
  import { selectAll, selectByCompanyId, save, selectStoreById } from '@/api/productService/product'
  import { quillEditor } from 'vue-quill-editor'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'

  export default {

    components: {
      quillEditor
    },
    props: {
      record: {
        default: ''
      }
    },
    data() {
      return {
        value: [],
        treeData: [],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        buttonCol: {
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 12, offset: 5 }
          }
        },
        storeIds: '',
        companyList: [],
        visible: false,
        form: this.$form.createForm(this),
        merchantList: [],
        previewImage: '',
        previewVisible: false,
        // mode: 'multiple',
        defaultCompany: '',
        //图片上传
        fileList: [],
        mdl: {},
        couponPicUrl: '',
        editorOption: {
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike', 'clean'],
              ['blockquote', 'code-block'],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'script': 'sub' }, { 'script': 'super' }],
              [{ 'indent': '-1' }, { 'indent': '+1' }],
              [{ 'direction': 'rtl' }],
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              [{ 'color': [] }, { 'background': [] }]
            ]
          }
        },
        content: ''
      }
    },
    watch: { //商户id
      value(value) {
        /* console.log("watch:",value)
         let arr = []
         if (value.length > 0) {
           value.forEach(function(elem) {
             arr.push(value.split('-')[value.length - 1])
           })
           this.storeIds = arr
         } else {
           this.storeIds = []
         }*/


      }
    },
    created() {
      const _this = this
      this.getAllCompany()
      if(this.record!=''){
        this.loadEditInfo(this.record)
      }
    },

    methods: {
      loadEditInfo(record) {
        record.value = record.storeCodes
        this.mdl = Object.assign({}, record)
        this.getAllCompany()
        this.isDisabled = true
        this.content = this.escapeStringHTML(record.note)
        if (record) {
          this.fileList = [{ 'uid': 123, 'url': record.couponPicUrl.toString(), 'name': '123' }]
        }
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(record, 'companyId', 'couponStockId', 'paySubMchId', 'name', 'type', 'value'))
        })

      },
      handleGoBack() {
        this.$emit('onGoBack')
      },
      uploadCancel() {
        this.previewVisible = false
      },
      getAllCompany: function() {
        const _this = this
        selectAll().then(res => {
          if (res.code === 200) {
            this.companyList = res.result
            this.defaultCompany = this.companyList[0].id
            let querycompanyId
            /*报错的原因*/
            if (_this.record.companyId != undefined) {
              /*不为空就执行编辑*/
              querycompanyId = _this.record.companyId
            } else {
              /!*为空就添加*!/
              querycompanyId = res.result[0].id
            }
            this.getAllMerchant(querycompanyId)
          } else {
            this.$notification.error({
              message: '错误',
              description: res.message,
              duration: 4
            })
          }
        })
      },
      onEditorBlur() {
      }, // 失去焦点事件
      onEditorFocus() {
      }, // 获得焦点事件
      onEditorChange() {
      }, // 内容改变事件
      // 转码
      escapeStringHTML(str) {
        if (str) {
          str = str.replace(/&lt;/g, '<')
          str = str.replace(/&gt;/g, '>')
          return str
        }

      },
      //公司改变
      handleProvinceChange(value) {
        if (value) {
          this.getAllMerchant(value)
        }
      },
      getAllMerchant: function(companyId) {
        const _this = this
        selectByCompanyId(companyId).then(res => {
          if (res.code === 200) {
            if (res.result == null) {
              return
            }
            _this.treeData = res.result
            /*编辑页面调用*/
            if (_this.record != '') {
              selectStoreById(_this.record.id).then(res => {
                _this.value = res.result
              })
            }

          } else {
            this.$notification.error({
              message: '错误',
              description: res.message,
              duration: 4
            })
          }
        })
      },
      uploadPreview(file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      },
      uploadChange(info) {
        const _this = this
        this.fileList = info.fileList
        if (info.file.status === 'done') {
          this.fileList.pop()
          this.fileList.push(info.file)
          _this.couponPicUrl = info.file.response.url
          this.$message.success(`${info.file.name} 上传成功`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败`)
        } else if (info.file.status === 'removed') {
          deletePic(info.file.uid).then(res => {
          })
        }
      },
      handleSubmit() {
        const _this = this
        // 触发表单验证
        _this.form.validateFields((err, values) => {
          if (!_this.couponPicUrl) { //如果是编辑页跳转 图片就为空
            values.couponPicUrl = _this.fileList[0].url
          } else {
            values.couponPicUrl = _this.couponPicUrl
          }

          let value = values.value

          let arr = []
          if (value.length > 0) {
            value.forEach(function(elem) {
              var split = elem.split('-')
              arr.push(parseInt(split[split.length - 1]))
            })
          }

          values.storeIds = arr
          values.value = ''
          values.id = _this.mdl.id
          // 验证表单没错误
          if (!err) {
            // 模拟后端请求 2000 毫秒延迟
            if (_this.content == '') {
              this.$notification.warning({
                message: '警告',
                description: '请先填写优惠券简介描述',
                duration: 4
              })
            } else if (!this.record && _this.fileList == '') {
              this.$notification.warning({
                message: '警告',
                description: '请先上传优惠券图片',
                duration: 4
              })
            } else {
              values.note = _this.content
              save(values).then((res) => {
                if (res.code === 200) {
                  _this.$message.success('添加成功')
                  this.$emit('onGoBack')
                } else {
                  this.$notification.error({
                    message: '错误',
                    description: res.message,
                    duration: 4
                  })
                }
              }).catch(() => {
                // Do something
              }).finally(() => {
                _this.confirmLoading = false
              })
            }
          }
        })

      }

    }

  }

</script>

<style>
  .ql-container {
    height: 300px;
  }
</style>